package ar.edu.itba.pod.legajo45129.balance.api;

import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import java.util.List;

import ar.edu.itba.node.Node;
import ar.edu.itba.node.NodeInformation;
import ar.edu.itba.node.api.NodeStatistics;
import ar.edu.itba.node.api.StatisticReports;
import ar.edu.itba.pod.agent.market.AgentState;
import ar.edu.itba.pod.agent.runner.Agent;
import ar.edu.itba.pod.agent.runner.Simulation;
import ar.edu.itba.pod.legajo45129.manager.NodeManager;

public class RemoteStatistics implements StatisticReports {
	private Simulation simulation;

	public RemoteStatistics(Simulation simulation)
			throws RemoteException {
		UnicastRemoteObject.exportObject(this, 0);
		NodeInformation localNode = NodeManager.getInstance()
				.getNodeInformation();
		Registry registry;
		registry = LocateRegistry.getRegistry(localNode.host(),
				localNode.port());
		if (registry == null) {
			registry = LocateRegistry.createRegistry(localNode.port());
		}

		registry.rebind(Node.STATISTIC_REPORTS, this);
		this.simulation = simulation;
	}

	@Override
	public NodeStatistics getNodeStatistics() throws RemoteException {
		List<AgentState> agentStates = new ArrayList<AgentState>();

		for (Agent a : simulation.getAgentsRunning()) {
			agentStates.add(a.state());
		}

		return new NodeStatistics(simulation.getAgentsRunning().size(),
				agentStates);
	}
}
